package com.hubiao.mail;


import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
 * @Author 朱兴邦
 * @CreateDate： 2020/11/10 10:13
 * @Version 1.0
 */
//@Slf4j
public class SendEmail {

    private final static String account = "邮箱";
    private final static String password = "密码";
    private static final String personal = "发送方名称";

    /**
     * 发送邮件到指定邮箱
     *
     * @param emailAccount 接收方邮箱
     * @param title        标题
     * @param content      发送内容
     */
    public static void sendEmailTxt(String emailAccount, String title, String content) {
        try {

            if (emailAccount == null || title == null || content == null) {
//                log.error("参数错误");
                return;
            }

            //创建一个配置文件并保存
            Properties properties = new Properties();
            properties.setProperty( "mail.host", "smtp.qq.com" );
            properties.setProperty( "mail.transport.protocol", "smtp" );
            properties.setProperty( "mail.smtp.auth", "true" );
            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts( true );
            properties.put( "mail.smtp.ssl.enable", "true" );
            properties.put( "mail.smtp.ssl.socketFactory", sf );
            //创建一个session对象
            Session session = Session.getDefaultInstance( properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication( account, password );
                }
            } );
            //开启debug模式
            session.setDebug( true );
            //获取连接对象
            Transport transport = session.getTransport();
            //连接服务器
            transport.connect( "smtp.qq.com", account, password );
            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage( session );
            //邮件发送人
            mimeMessage.setFrom( new InternetAddress( account, personal, "UTF-8" ) );
//            //邮件接收人
//            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAccount));

            // 收件人
            mimeMessage.setRecipient( MimeMessage.RecipientType.TO, new InternetAddress( emailAccount, "USER_CC", "UTF-8" ) );
            // 增加收件人（可选）
//            mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("dd@receive.com", "USER_DD", "UTF-8"));
            // 抄送（可选）
//            mimeMessage.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("ee@receive.com", "USER_EE", "UTF-8"));
            // 密送（可选）
//            mimeMessage.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@receive.com", "USER_FF", "UTF-8"));

            //邮件标题
            mimeMessage.setSubject( title );
            //邮件内容
            mimeMessage.setContent( content, "text/html;charset=UTF-8" );
            // 6. 设置显示的发件时间
            mimeMessage.setSentDate( new Date() );
            //发送邮件
            transport.sendMessage( mimeMessage, mimeMessage.getAllRecipients() );
            //关闭连接
            transport.close();
        } catch (Exception e) {
//            log.error("邮件发送失败");
            return;
        }
    }

    public static void sendEmailFile(String emailAccount, String title, String content) {
        try {
            Properties prop = new Properties();
            prop.setProperty( "mail.host", "smtp.qq.com" );  //设置QQ邮件服务器
            prop.setProperty( "mail.transport.protocol", "smtp" ); // 邮件发送协议
            prop.setProperty( "mail.smtp.auth", "true" ); // 需要验证用户名密码

            // QQ邮箱设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts( true );
            prop.put( "mail.smtp.ssl.enable", "true" );
            prop.put( "mail.smtp.ssl.socketFactory", sf );

            //1、创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getDefaultInstance( prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    //传入发件人的姓名和授权码
                    return new PasswordAuthentication( account, password );
                }
            } );

            //2、通过session获取transport对象
            Transport transport = session.getTransport();

            //3、通过transport对象邮箱用户名和授权码连接邮箱服务器
            transport.connect( "smtp.qq.com", account, password );

            //4、创建邮件,传入session对象
//            MimeMessage mimeMessage = complexEmail(session, emailAccount, title, content);

            //5、发送邮件
//            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

            //6、关闭连接
            transport.close();
        } catch (Exception e) {
//            log.error("邮件发送失败");
//            throw new BusinessException("邮件发送失败");
        }
    }

    public static void complexEmail(Session session, String emailAccount, String title, String content) {
        try {
            //消息的固定信息
            MimeMessage mimeMessage = new MimeMessage( session );

            //发件人
            mimeMessage.setFrom( new InternetAddress( account, personal, "UTF-8" ) );
            //收件人
            mimeMessage.setRecipient( Message.RecipientType.TO, new InternetAddress( emailAccount, "USER_CC", "UTF-8" ) );
            //邮件标题
            mimeMessage.setSubject( title );

            //邮件内容
            //准备图片数据
            MimeBodyPart image = new MimeBodyPart();
            DataHandler handler = new DataHandler( new FileDataSource( "E:\\draft\\file\\7697325_211249288171_2.jpg" ) );
            image.setDataHandler( handler );
            image.setContentID( "7697325_211249288171_2.jpg" ); //设置图片id

            //准备文本
            MimeBodyPart text = new MimeBodyPart();
            text.setContent( content + ":<img src='cid:7697325_211249288171_2.jpg'>", "text/html;charset=utf-8" );

            //附件
            MimeBodyPart appendix = new MimeBodyPart();
            appendix.setDataHandler( new DataHandler( new FileDataSource( "E:\\draft\\file\\aaaaaa.txt" ) ) );
            appendix.setFileName( "aaaaaa.txt" );

            //拼装邮件正文
            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart( image );
            mimeMultipart.addBodyPart( text );
            mimeMultipart.setSubType( "related" );//文本和图片内嵌成功

            //将拼装好的正文内容设置为主体
            MimeBodyPart contentText = new MimeBodyPart();
            contentText.setContent( mimeMultipart );

            //拼接附件
            MimeMultipart allFile = new MimeMultipart();
            allFile.addBodyPart( appendix );//附件
            allFile.addBodyPart( contentText );//正文
            allFile.setSubType( "mixed" ); //正文和附件都存在邮件中，所有类型设置为mixed


            //放到Message消息中
            mimeMessage.setContent( allFile );
            mimeMessage.saveChanges();//保存修改

        } catch (Exception e) {
//            log.error("发送附件邮件失败", e);
//            throw new BusinessException("发送附件邮件失败,接收方账户:" + emailAccount);
        }
    }
}

